#!/usr/bin/env python3
from PIL import ImageFont,Image,ImageDraw
import sys

class Tiff_Gen:
    """
    字体大小 size
    每行20个字，每字间隔20 -- 页宽 (20+size)*20+20
    每页行数根据总字数定，行间距20    -- N*(20+size)+20
    """
    text = '天地玄黄，ABCD。'
    size = 60
    index = 0
    def __init__(self,truetype_path='/usr/share/fonts/truetype/wqy/wqy-microhei.ttc'):
        self.font = ImageFont.truetype(font=truetype_path,size=self.size)
    def get_words(self,path='words.txt'):
        fp = open(path,'r')
        data = []
        for item in fp:
            data.append( ''.join( item.split() ) )
        fp.close()
        self.text = ''.join( data )
    def gen_img(self):
        n = len(self.text)/20
        if n>int(n):
            n=int(n)+1
        else:
            n=int(n)
        self.index = 0
        height = n*(20+self.size) + 20
        width = (20+self.size)*20+20
        fp=open('output.txt','w')
        fp.write( self.text + '\n' )
        fp.close()
        image = Image.new( '1',(width,height),color=255 )
        draw = ImageDraw.ImageDraw( image )
        self.w = width
        self.h = height
        fp=open('box','w')
        while self.index<len(self.text):
            x = (self.index%20)*(20+self.size) + 20
            y = (self.index//20)*(20+self.size) + 20
            xy = (x,y)
            draw.text(xy,self.text[self.index],fill=0,font=self.font)
            size1 = self.font.getsize( self.text[self.index] )
            #第一点：左下(x , self.h-y-size1[1])，第二点：右上(x+size1[0] , self.h-y)
            fp.write('%s %s %s %s %s 0\n'%(self.text[self.index],x,self.h-y-size1[1],x+size1[0],self.h-y))
            self.index += 1
        fp.close()
        fp = open('output.tiff','wb')
        image.save(fp,format='TIFF')
        fp.close()
        print(str(self.font.getname()))

if __name__ == '__main__':
    ttf = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
    if len(sys.argv)==2:
        ttf = sys.argv[1]
    print(ttf)
    obj = Tiff_Gen( ttf )
    filename = input("输入文件名：")
    obj.get_words( filename )
    obj.gen_img()
